package com.example.eazytransfer.ui;

import com.example.eazytransfer.model.TCPUtil;
import com.example.eazytransfer.model.ViewModel;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import javafx.stage.FileChooser;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

public class SendFileController implements Initializable {

    @FXML
    private ListView<String> lvSendFile;
    @FXML
    private Label labelSendingFile;
    @FXML
    private Label labelProgressSend;
    @FXML
    private ProgressBar progressBarSend;
    @FXML
    private Button btnAdd;
    @FXML
    private Button btnSend;
    @FXML
    private Button btnRemove;

    @FXML
    private Pane root;

    @FXML
    protected void addFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("添加文件");
        List<File> files = fileChooser.showOpenMultipleDialog(root.getScene().getWindow());
        if (files != null)
            for (File file : files) {
                ViewModel.getInstance().filePathListForSend.add(file.getAbsolutePath());
            }

    }

    @FXML
    protected void removeFileItem() {
        if (ViewModel.getInstance().filePathItemBeSelected.get() == null) return;
        ViewModel.getInstance().filePathListForSend.remove(ViewModel.getInstance().filePathItemBeSelected.get());
    }

    @FXML
    protected void send() {
        if (!ViewModel.getInstance().isConnected.get()) return;
        Iterator<String> iterator = ViewModel.getInstance().filePathListForSend.iterator();
        while (iterator.hasNext()) {
            String fp = iterator.next();
            TCPUtil.getInstance().sendFile(fp);
        }
    }


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        lvSendFile.setItems(ViewModel.getInstance().filePathListForSend);
        lvSendFile.getSelectionModel().selectedItemProperty().addListener((observableValue, s, t1) -> ViewModel.getInstance().filePathItemBeSelected.set(t1));
        progressBarSend.progressProperty().bindBidirectional(ViewModel.getInstance().sendingProgress);
        labelProgressSend.textProperty().bindBidirectional(ViewModel.getInstance().sendingProgressPercent);
        labelSendingFile.textProperty().bindBidirectional(ViewModel.getInstance().filePathOnSending);
        ViewModel.getInstance().filePathOnSending.set("无");
        ViewModel.getInstance().sendingProgress.set(0);
        ViewModel.getInstance().sendingProgressPercent.set("0%");
    }
}
